package com.imaker.service;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.imaker.dao.BaseDao;
import com.imaker.domain.Department;
import com.imaker.domain.Page;
import com.imaker.domain.UserInfo;
import com.imaker.field.StaticField;

 /**
 * <p>程序名称：      UserService.java</p>
 * <p>程序说明：       TODO</p>
 * <p>版权信息：       Copyright mayonghua</p>
 * 
 * @author：          mayonghua
 * @version：         Ver 0.1
 */
@Service
public class UserService implements IService {
	private BaseDao<UserInfo> userDAO = null;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		userDAO = new BaseDao<UserInfo>(sessionFactory,UserInfo.class);
	}
	
	public String save(UserInfo userInfo){
		try{
			userDAO.save(userInfo);	
		}catch(Exception e){
			e.printStackTrace();
			return StaticField.error;
		}
		return StaticField.success;
	}
	
	/**
	 * 查询所有
	 * @return
	 * @throws Exception
	 */
	public List<UserInfo> findAll() throws Exception{
		return userDAO.findAll();
	}
	
	/**
	 * 判断用户登录
	 * @return
	 * @throws Exception
	 */
	public UserInfo findByProperty(String userName,String password) throws Exception {
		String hql = "from UserInfo u where u.userName = ? and u.passWord = ?";
		List<UserInfo> list = userDAO.find(hql,userName,password);
		if(list.size()>0){
			return list.get(0);
		}else {
			return null;
		}
	}
	
	/**
	 * 根据ID进行查找
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	public UserInfo findById(String id) throws Exception{
		return userDAO.get(id);
	}
	
	/**
	 * 删除
	 */
	public String delete(List idList){
		try {
			userDAO.deleteByIdList(idList);
		} catch (Exception e) {
			e.printStackTrace();
			return StaticField.error;
		}
		return StaticField.success;
	}
	
	/**
	 * 更新
	 */
	public String update(UserInfo userInfo){
		try {
			userDAO.update(userInfo);
		} catch (Exception e) {
			e.printStackTrace();
			return StaticField.error;
		}
		return StaticField.success;
	}
	
	/**
	 * 分页查找
	 */
	public Page listByPage(Page page,Department department) throws Exception{
		String hql = "from UserInfo u where u.department.id = ?";
		return userDAO.pagination(page, hql,"",department.getId());
	}
}
